package com.yjc.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yjc.springcloud.alibaba.service.PaymentService;
import com.yjc.springcloud.bean.CommotResult;
import com.yjc.springcloud.bean.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author shkstart
 * @create 2022-08-16 16:57
 */
@RestController
@Slf4j
public class CircleBreakerController {


    @Autowired
    public RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    public String service_url;

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback",
            fallback = "fallbackHandler",
            blockHandler = "blockHandler",
            exceptionsToIgnore = {IllegalArgumentException.class})
    public CommotResult<Payment> fallback(@PathVariable("id") Long id) {
        CommotResult res = restTemplate.getForObject(service_url + "/paymentSQL/" + id, CommotResult.class);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常...");
        } else if (res.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录，空指针异常");
        }
        return res;
    }

    //fallbackHandler
    public CommotResult<Payment> fallbackHandler(@PathVariable("id") Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommotResult<>(4444, "fallback处理异常, fallbackHandler, 异常为：" + e.getMessage(), payment);
    }

    //blockHandler
    public CommotResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e) {
        Payment payment = new Payment(id, "null");
        return new CommotResult<>(4445, "block处理限流异常, blockHandler, 异常为：" + e.getMessage(), payment);
    }

    //////OpenFeign////////

    @Autowired
//    @Qualifier("paymentServiceImpl")
    PaymentService paymentService;

    @GetMapping("/consumer/paymentSQL/{id}")
    public CommotResult<Payment> feignPayment(@PathVariable("id") Long id) {
        return paymentService.paymentSQL(id);
    }

}
